Core Java Interview Questions

Ratings:
(4)
Views: 542
Banner-Img
Share this blog:

Core Java Interview Questions and Answers

Q1) Which two methods you need to implement for key Object in HashMap?

Ans:  To use any object as a Key in HashMap, it must implement equals and hashcode method in Java. Read How HashMap works in Java for a detailed explanation of how the equals and hashcode method is used to put and get an object from HashMap.

Q2) What is an immutable object? Can you write an immutable object?

Ans:  Immutable classes are Java classes whose objects can not be modified once created. Any modification in an Immutable object results in a new object. For example, is String is immutable in Java. Mostly Immutable are also final in Java, to prevent sub class from overriding methods in Java which can compromise Immutability. You can achieve the same functionality by making members nonfinal but private and not modifying them except in the constructor.

Q3) What is the difference between creating String as new() and literal?

Ans:  When we create a string with a new() Operator, it’s created in the heap and not added into the string pool while String created using literal are created in the String pool itself which exists in the PermGen area of the heap.

String s = new String("Test");

does not put the object in the String pool, we need to call String.intern() method which is used to put them into the String pool explicitly. it's only when you create a String object as String literal e.g. String s = "Test" Java automatically put that into the String pool.

Q4) What is the difference between StringBuffer and StringBuilder in Java?

Ans:  Classic Java questions which some people think tricky and some consider very easy. StringBuilder in Java is introduced in Java 5 and the only difference between both of them is that StringBuffer methods are synchronized while StringBuilder is non synchronized. See StringBuilder vs StringBuffer for more differences.

Q5) Write code to find the First non repeated character in the String?

Ans:  Another good Java interview question, This question is mainly asked by Amazon and equivalent companies. See first non repeated character in the string: Amazon interview question

Q6) What is the difference between ArrayList and Vector?

Ans:  This question is mostly used as a start up question in Technical interviews on the topic of Collection framework. The answer is explained in detail here the Difference between ArrayList and Vector.

Q7) How do you handle error conditions while writing a stored procedure or accessing a stored procedure from java?

Ans:  This is one of the tough Java interview questions and it's open for all, my friend didn't know the answer so he didn't mind telling me. my take is that stored procedure should return an error code if some operation fails but if the stored procedure itself fails then catching SQLException is the only choice.

Q8) What is difference between Executor.submit() and Executer.execute() method ?

Ans:  There is a difference when looking at exception handling. If your tasks throw an exception and if it was submitted with executing this exception will go to the uncaught exception handler (when you don't have provided one explicitly, the default one will just print the stack trace to System.err). If you submitted the task with submitting any thrown exception, checked exception or not, is then part of the task's return status. For a task that was submitted with submitting and that terminates with an exception, the Future.get will re-throw this exception, wrapped in an ExecutionException.

Q9) What is the difference between factory and abstract factory pattern?

Ans:

  • Abstract Factory provides one more level of abstraction. Consider different factories each extended from an Abstract Factory and responsible for the creation of different hierarchies of objects based on the type of factory. E.g. Abstract Factory extended by Automobile Factory, UserFactory, Role Factory, etc. Each factory would be responsible for the creation of objects in that genre.
  • You can also refer to What is Factory method design pattern in Java to know more details.

Q10) What is Singleton? is it better to make the whole method synchronized or only the critical section synchronized?

Ans:  Singleton in Java is a class with just one instance in the whole Java application, for example, java.lang.Runtime is a Singleton class. Creating Singleton was tricky before Java 4 but once Java 5 introduced Enum it's very easy. see my article How to create thread-safe Singleton in Java for more details on writing Singleton using enum and double-checked locking which is the purpose of this Java interview question.

Q11) Can you write a critical section code for singleton?

Ans:  This core Java question is a follow-up of the previous question and expecting a candidate to write Java singleton using double-checked locking. Remember to use volatile variables to make Singleton thread-safe.

Q12) Can you write code for iterating over hashmap in Java 4 and Java 5?

Ans:  Tricky one but he managed to write using a while and for a loop.

Q13) When do you override hashcode and equals()?

Ans: Whenever necessary especially if you want to do an equality check or want to use your object as a key in HashMap.

Q14) What will be the problem if you don't override the hashcode() method?

Ans:  You will not be able to recover your object from hash Map if that is used as a key in HashMap. See here  How HashMap works in Java for a detailed explanation.

Q15) Is it better to synchronize critical section of getInstance() method or whole getInstance() method ?

Ans:  The answer is a critical section because if we lock the whole method than every time someone calls this method will have to wait even though we are not creating any object)

Q16) What is the difference when String is gets created using a literal or new() operator?

Ans:  When we create a string with new() its created in the heap and not added into the string pool while String created using literal are created in the String pool itself which exists in the Perm area of the heap.

Q17) Does not override the hashcode() method has any performance implication?

Ans:  This is a good question and opens to all, as per my knowledge, a poor hashcode function will result in frequent collision in HashMap which eventually increases the time for adding an object into Hash Map.

Q18) What’s wrong with using HashMap in a multithreaded environment? When get() method go to an infinite loop?

Ans:  Another good question. His answer was during concurrent access and re-sizing.

Q19) What do you understand by thread-safety? Why is it required? And finally, how to achieve thread-safety in Java Applications?

Ans: 

  • Java Memory Model defines the legal interaction of threads with the memory in a real computer system. In a way, it describes what behaviors are legal in multi-threaded code. It determines when a Thread can reliably see writes to variables made by other threads. It defines semantics for volatile, final & synchronized, which makes guarantee visibility of memory operations across the Threads.
  • Let's first discuss Memory Barrier which is the base for our further discussions. There are two types of memory barrier instructions in JMM:

            1. Read barriers 

            2. Write barriers.

  • A read barrier invalidates the local memory (cache, registers, etc) and then reads the contents from the main memory so that changes made by other threads become visible to the current Thread.
  • A write barrier flushes out the contents of the processor's local memory to the main memory, so that changes made by the current Thread becomes visible to the other threads.

Inclined to build a profession as core java training? Then here is the blog post on, explore core java training

JMM semantics for synchronized

When a thread acquires a monitor of an object, by entering into a synchronized block of code, it performs a read barrier (invalidates the local memory and reads from the heap instead). Similarly exiting from a synchronized block as part of releasing the associated monitor, it performs a write barrier (flushes changes to the main memory) Thus modifications to a shared state using synchronized block by one Thread, are guaranteed to be visible to subsequent synchronized reads by other threads. This guarantee is provided by JMM in presence of a synchronized code block.

JMM semantics for Volatile  fields

Read & write to volatile variables have the same memory semantics as that of acquiring and releasing a monitor using a synchronized code block. So the visibility of the volatile field is guaranteed by the JMM. Moreover afterward Java 1.5, volatile reads and writes are not reorderable with any other memory operations (volatile and non-volatile both). Thus when Thread A writes to a volatile variable V, and afterward Thread B reads from variable V, any variable values that were visible to A at the time V was written are guaranteed now to be visible to B.

Let's try to understand the same using the following code

Data data = null;

volatile boolean flag = false;

Thread A

-------------

data = new Data();

flag = true; <-- writing to volatile will flush data as well as a flag to main memory

Thread B

-------------

if(flag==true){ <-- as="" barrier="" data.="" flag="" font="" for="" from="" perform="" read="" reading="" volatile="" well="" will="">

use data; <!--- data is guaranteed to visible even though it is not declared volatile because of the JMM semantics of volatile flag.

Q20) What will happen if you call return statement or System.exit on the try or catch block? will finally block execute?

Ans:  This is a very popular tricky Java question and it's tricky because many programmers think that finally block always executed. This question challenge that concept by putting a return statement in try or catch block or calling System.exit from try or catch block. The answer to this tricky question in Java is that finally block will execute even if you put a return statement in the try block or catch block but finally block won't run if you call System.exit from trying or catch.

Q21) Can you override private or static methods in Java?

Ans:  Another popular Java tricky question, As I said method overriding is a good topic to ask trick questions in Java.  Anyway, you can not override private or static method in Java, if you create a similar method with the same return type and same method arguments that are called method hiding.

Q22) What will happen if we put a key object in a HashMap which is already there?

Ans:  This tricky Java question is part of How HashMap works in Java, which is also a popular topic to create confusing and tricky questions in Java. well if you put the same key again then it will replace the old mapping because HashMap doesn't allow duplicate keys. 

Q23) If a method throws NullPointerException in the superclass, can we override it with a method that throws RuntimeException?

Ans:  One more tricky Java question from overloading and overriding concept. The answer is you can very well throw superclass of RuntimeException in the overridden method but you can not do the same if it's checked Exception. 

Q24) What is the issue with the following implementation of the compareTo() method in Java

Ans:  public int compareTo(Object o)

         {

         Employee emp = (Employee) emp;

         return this.id - o.id;

          }

Q25) How do you ensure that the N thread can access N resources without deadlock?

Ans:  If you are not well versed in writing multi-threading code then this is a really tricky question for you. This Java question can be tricky even for the experienced and senior programmers, who are not really exposed to deadlock and race conditions. The key point here is order, if you acquire resources in a particular order and release resources in the reverse order you can prevent deadlock. 

Q26) What is the difference between CyclicBarrier and CountDownLatch in Java?

Ans:  Relatively newer Java tricky question, only been introduced from Java 5. The main difference between both of them is that you can reuse CyclicBarrier even if the Barrier is broken but you can not reuse CountDownLatch in Java. See CyclicBarrier vs CountDownLatch in Java for more differences.

Q27) Can you access nonstatic variables in a static context?

Ans:  Another tricky Java question from Java fundamentals. No, you can not access static variables in the nonstatic context in Java. Read why you can not access the non-static variables from a static method to learn more about these tricky Java questions.

Q28) How many types of memory areas are allocated by JVM?

Ans:  Many types:

  • Class(Method) Area
  • Heap
  • Stack
  • Program Counter Register
  • Native Method Stack

Q29) What is the JIT compiler?

Ans: Just-In-Time(JIT) compiler: It is used to improve performance. JIT compiles parts of the byte code that have similar functionality at the same time, and hence reduces the amount of time needed for compilation. Here the term “compiler” refers to a translator from the instruction set of a Java virtual machine (JVM) to the instruction set of a specific CPU.

Q30) What is a platform?

Ans:  A platform is basically the hardware or software environment in which a program runs. There are two types of platforms software-based and hardware-based. Java provides a software-based platform.

Q31) What is the main difference between the Java platform and other platforms?

Ans:  The Java platform differs from most other platforms in the sense that it's a software-based platform that runs on top of other hardware-based platforms. It has two components:

  • Runtime Environment
  • API (Application Programming Interface)

Q32) What gives Java its 'write once and run anywhere' nature?

Ans:  The bytecode. Java is compiled to be a byte code which is the intermediate language between source code and machine code. This byte code is not platform specific and hence can be fed to any platform.

Q33) What is a static variable?

Ans:  A static variable is used to refer to the common property of all objects (that is not unique for each object) e.g. company name of employees, college name of students, etc. static variable gets memory only once in the class area at the time of class loading. more details.

Q34) What is a static method?

Ans:  A static method belongs to the class rather than the object of a class. A static method can be invoked without the need for creating an instance of a class. a static method can access static data member and can change the value of it. more details.

Q35) Why the main method is static?

Ans:  Because the object is not required to call a static method if It were a non-static method, JVM creates an object first then calls a main() method that will lead to the problem of extra memory allocation more details.

Q36) What is a static block?

Ans: This is used to initialize the static data member. It is executed before the main method at the time of classloading.

Core Java Tutorials

You liked the article?

Like: 2

Vote for difficulty

Current difficulty (Avg): Medium

EasyMediumHardDifficultExpert
IMPROVE ARTICLEReport Issue

About Author

Authorlogo
Name
TekSlate
Author Bio

TekSlate is the best online training provider in delivering world-class IT skills to individuals and corporates from all parts of the globe. We are proven experts in accumulating every need of an IT skills upgrade aspirant and have delivered excellent services. We aim to bring you all the essentials to learn and master new technologies in the market with our articles, blogs, and videos. Build your career success with us, enhancing most in-demand skills in the market.

Stay Updated
Get stories of change makers and innovators from the startup ecosystem in your inbox